package com.example.childcheck;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.baidu.geofence.GeoFence;
import com.baidu.geofence.GeoFenceClient;
import com.baidu.geofence.GeoFenceListener;
import com.baidu.geofence.model.DPoint;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class Map_find_Activity extends AppCompatActivity implements BaiduMap.OnMapLongClickListener {

    private static final String GEOFENCE_BROADCAST_ACTION = "";
    private MapView mMapView = null;
    public BaiduMap baiduMap = null;
    public static double v,v1;
    //public static double c1=118.09382,c2=24.63066;
    public double latitude;   //长按的经度
    public double longitude;//  长按的纬度
    private Socket socket;

    public static LatLng safe;
    public static int radius=0;
    public static boolean isset=false;

    public static final String CHANNEL_ID = "my_channel_id";
    public static final int NOTIFICATION_ID = 1;

    LocationClient mLocationClient = null;

    private String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private static final int OPEN_SET_REQUEST_CODE = 100;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        LocationClient.setAgreePrivacy(true);
        setContentView(R.layout.activity_map_find);
        //mMapView = (MapView) findViewById(R.id.bmapView);

        /*baiduMap=mMapView.getMap();//获取地图控制器
        // 3.  设置地图中心点为target
        MapStatusUpdate mapStatusUpdate= MapStatusUpdateFactory.newLatLng(target);
        baiduMap.setMapStatus(mapStatusUpdate);
        //4.   设置地图缩放为15
        mapStatusUpdate= MapStatusUpdateFactory.zoomTo(15);
        baiduMap.setMapStatus(mapStatusUpdate);
        mMapView.removeViewAt(1);

        LatLng lng_c =new LatLng(c1,c2);
        BitmapDescriptor mark_c=BitmapDescriptorFactory.fromResource(R.drawable.childmark);
        MarkerOptions childmark = new MarkerOptions().position(lng_c).icon(mark_c).scaleX(0.3f).scaleY(0.3f);
        baiduMap.addOverlay(childmark);*/
        initPermissions();
        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.bmapView);
        //获取到地图
        baiduMap = mMapView.getMap();
        //设置地图放大的倍数
        init();
        //设置地图定位的一些参数，如定位图标，精度圈颜色等
        //configure();

        //定位初始化
        init_location();
        LatLng target = new LatLng(v, v1);
        MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLng(target);
        baiduMap.setMapStatus(mapStatusUpdate);

        baiduMap.setOnMapLongClickListener(this);

    }
    //这个函数使用传入的经纬度绘制标记
    public void setchildMark(double c11,double c22) {

        LatLng lng_c =new LatLng(c22,c11);
        BitmapDescriptor mark_c=BitmapDescriptorFactory.fromResource(R.drawable.childmark);
        MarkerOptions childmark = new MarkerOptions().position(lng_c).icon(mark_c).scaleX(0.3f).scaleY(0.3f);
        del();
        if(isset==true) {
            drawcircle(safe);
        }
        baiduMap.addOverlay(childmark);
    }

    //使用传入地址添加圆形覆盖物
    public void drawcircle(LatLng circlepoint){

        CircleOptions circle=new CircleOptions().center(circlepoint).radius(radius)
                .fillColor(Color.argb(100,152, 251, 152));
        baiduMap.addOverlay(circle);
    }


    public void del(){
       baiduMap.clear();
    }

    public void getmark(){

        new Thread(new Runnable() {
            double d1,d2,distance;
            @Override
            public void run() {
                try {
                    // 创建一个 Socket 对象，并指定远程服务器的 IP 地址和端口号
                    socket = new Socket("192.168.56.199",8888);
                    DataInputStream in = new DataInputStream(socket.getInputStream());
                    String data = in.readUTF();
                    String[] values = data.split(",");
                    if (values.length == 2) {
                        d1 = Double.parseDouble(values[0]);
                        d2 = Double.parseDouble(values[1]);
                        setchildMark(d1,d2);
                        LatLng child=new LatLng(d2,d1);
                        if(isset){
                            distance=DistanceUtil.getDistance(child,safe);
                            if(distance>(double)radius){
                                noteshow();
                                warn();
                            }
                        }
                    }
                    // 使用完毕后，需要关闭 Socket 对象
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    public void warn(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String THINGSBOARD_URL = "http://192.168.56.199:8080/api/v1/{access_token}/telemetry";
                String ACCESS_TOKEN = "v8GDQAcnOQK25ZSzACTJ";
                try {
                    URL url = new URL(THINGSBOARD_URL.replace("{access_token}", ACCESS_TOKEN));
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/json");
                    conn.setRequestProperty("Accept", "application/json");
                    conn.setRequestProperty("X-Authorization", "Bearer " + ACCESS_TOKEN);
                    conn.setDoOutput(true);

                    // 要发送的数据
                    String data = "{\"gaojing\": true}";
                    // 发送HTTP POST请求
                    conn.getOutputStream().write(data.getBytes());

                    conn.disconnect();

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        /*super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();*/
        mLocationClient.stop();
        baiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            v = location.getLatitude();
            v1 = location.getLongitude();

            getmark();
            warn();

            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(location.getDirection()).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            baiduMap.setMyLocationData(locData);
        }
    }

    /**
     * 设置地图放大的倍数
     */
    public void init() {
        //设置地图放大的倍数
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.zoom(15);
        baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
    }

    /**
     * 自定义内容:
     * 参数说明
     * (1)定位模式 地图SDK支持三种定位模式：NORMAL（普通态）, FOLLOWING（跟随态）, COMPASS（罗盘态）
     * （2）是否开启方向
     * （3）自定义定位图标 支持自定义定位图标样式，
     * （4）自定义精度圈填充颜色
     * （5）自定义精度圈边框颜色
     */
    public void configure() {
        baiduMap.setMyLocationConfiguration(new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true,
                BitmapDescriptorFactory.fromResource(R.drawable.parentmark),
                0xAAFFFF88, 0xAA00FF00));
    }


    /**
     * 定位的初始化
     */
    public void init_location() {
        baiduMap.setMyLocationEnabled(true);
        mLocationClient = new LocationClient(Map_find_Activity.this);
//通过LocationClientOption设置LocationClient相关参数
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
//设置locationClientOption
        mLocationClient.setLocOption(option);
//注册LocationListener监听器
        MyLocationListener myLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myLocationListener);
//开启地图定位图层
        mLocationClient.start();
    }


    //调用此方法判断是否拥有权限
    private void initPermissions() {
        if (lacksPermission(permissions)) {//判断是否拥有权限
            //请求权限，第二参数权限String数据，第三个参数是请求码便于在onRequestPermissionsResult 方法中根据code进行判断
            ActivityCompat.requestPermissions(Map_find_Activity.this, permissions, OPEN_SET_REQUEST_CODE);
        } else {
            //拥有权限执行操作
            //init_location();
        }
    }

    //如果返回true表示缺少权限
    public boolean lacksPermission(String[] permissions) {
        for (String permission : permissions) {
            //判断是否缺少权限，true=缺少权限
            if (ContextCompat.checkSelfPermission(Map_find_Activity.this, permission) != PackageManager.PERMISSION_GRANTED) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onMapLongClick(LatLng lan){
            AlertDialog.Builder check=new AlertDialog.Builder(this);
            check.setTitle("请输入围栏半径:");
            final EditText input = new EditText(this);
            input.setInputType(InputType.TYPE_CLASS_NUMBER);
            check.setView(input);
            check.setPositiveButton("确定", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which){
                        safe=lan;
                        String text = input.getText().toString();
                        radius=Integer.parseInt(text);
                        del();
                        drawcircle(lan);
                        isset=true;
                    }
            });
             check.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //dialog.cancel();
                Toast.makeText(Map_find_Activity.this, "取消建立围栏", Toast.LENGTH_SHORT).show();
            }
        });
        check.show();
    }

    public void noteshow(){
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.parentmark)
                .setContentTitle("警告")
                .setContentText("您的孩子已经离开围栏范围")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);

//设置点击通知后的操作
        Intent intent = new Intent(this, Map_find_Activity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);

//在通知栏中显示通知
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        notificationManager.notify(NOTIFICATION_ID, builder.build());
    }


}